# coding: utf-8
from PyQt5 import QtGui, QtWidgets, QtCore
import config
from ui_design.main import Ui_MainWindow as __MainWindowForm
from utils import AbstractFunction
import icons_rc
import os
from Bayesian import Bayes
from widget_config import ConfigDialog


class GifPlayer(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super().__init__(parent=parent, flags=QtCore.Qt.FramelessWindowHint)
        self.setStyleSheet('background: transparent;')
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.movie = QtGui.QMovie(':icons/loading.gif', QtCore.QByteArray(), self)
        self.movie_screen = QtWidgets.QLabel()
        self.movie_screen.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        self.movie_screen.setAlignment(QtCore.Qt.AlignCenter)
        main_layout = QtWidgets.QVBoxLayout()
        main_layout.addWidget(self.movie_screen)
        self.setLayout(main_layout)
        self.movie.setCacheMode(QtGui.QMovie.CacheAll)
        self.movie_screen.setMovie(self.movie)
        self.movie.start()
        self.movie.loopCount()

    def keyPressEvent(self, event):
        if not event.key() == QtCore.Qt.Key_Escape:
            super(self.__class__, self).keyPressEvent(event)


class ImageCompareService(QtCore.QThread):
    sig_error = QtCore.pyqtSignal(str)
    sig_top_6 = QtCore.pyqtSignal(list)

    def __init__(self, parent):
        super(ImageCompareService, self).__init__(parent)
        self.bayesian_obj: Bayes = None
        self.chosen_ls: list = []
        self.action: str = ''

    def load(self, obj: Bayes, ls: list, action: str):
        self.bayesian_obj = obj
        self.chosen_ls = ls
        self.action = action

    def run(self) -> None:
        try:
            if self.action == 'init':
                self.bayesian_obj.init_probability()
            else:
                self.bayesian_obj.bayes_judge(str_cho=self.chosen_ls)
            self.sig_top_6.emit(self.bayesian_obj.get_top_6())
        except:
            self.sig_error.emit('出现错误')


class MainApp(QtWidgets.QMainWindow, __MainWindowForm, AbstractFunction):
    def __init__(self):
        super(MainApp, self).__init__()
        self.setupUi(self)

        self.bayesian_obj: Bayes = None
        self.data_goal: str = ''
        self.data_base: str = ''
        self.latest_top_6 = []

        self.init_image_viewers()
        self.gif_animation = GifPlayer(self)
        self.service = ImageCompareService(self)
        self.service.sig_error.connect(self.handle_receive_error)
        self.service.sig_top_6.connect(self.handle_receive_top_6)
        self.action_setup.triggered.connect(self.handle_config_project)
        self.action_quit.triggered.connect(self.handle_quit)
        self.actionabout_app.triggered.connect(self.display_app_info)
        self.actionabout_author.triggered.connect(self.display_author_info)
        self.btn_init.clicked.connect(self.handle_init_project)
        self.btn_continue.clicked.connect(self.handle_continue_process)
        self.btn_stop.clicked.connect(self.handle_quit)

        self.setMinimumSize(1024, 600)

    def handle_config_project(self):
        d = ConfigDialog(image_goal=self.data_goal, image_base=self.data_base, parent=self)
        r = d.exec_()
        if r == 1:
            self.data_base = d.data_base
            self.data_goal = d.data_goal
            self.init_image_viewers()
            self.bayesian_obj = None

    def init_image_viewers(self):
        self.viewer_1.clear_pix()
        self.viewer_2.clear_pix()
        self.viewer_3.clear_pix()
        self.viewer_4.clear_pix()
        self.viewer_5.clear_pix()
        self.viewer_6.clear_pix()

        self.group_box_1.setChecked(False)
        self.group_box_2.setChecked(False)
        self.group_box_3.setChecked(False)
        self.group_box_4.setChecked(False)
        self.group_box_5.setChecked(False)
        self.group_box_6.setChecked(False)
        self.latest_top_6 = []

    def display_images(self, image_ls):
        self.init_image_viewers()
        self.viewer_1.display_pix(QtGui.QPixmap(image_ls[0]))
        self.viewer_2.display_pix(QtGui.QPixmap(image_ls[1]))
        self.viewer_3.display_pix(QtGui.QPixmap(image_ls[2]))
        self.viewer_4.display_pix(QtGui.QPixmap(image_ls[3]))
        self.viewer_5.display_pix(QtGui.QPixmap(image_ls[4]))
        self.viewer_6.display_pix(QtGui.QPixmap(image_ls[5]))
        self.latest_top_6 = image_ls

    def handle_quit(self):
        r = self.show_warning_message(message='确定退出吗？', title='即将退出系统', parent=self)
        if r:
            self.close()

    def handle_init_project(self):
        if not self.data_goal:
            self.show_warning_message(message='请先配置项目', parent=self, only_yes=True)
            self.handle_config_project()
            if not self.data_goal:
                return
        self.bayesian_obj = Bayes(init_image=self.data_goal, image_dir=self.data_base)
        self.service.load(obj=self.bayesian_obj, ls=[], action='init')
        self.service.start()
        self.init_image_viewers()
        self.gif_animation.exec_()

    def handle_receive_error(self, msg):
        self.gif_animation.accept()
        self.show_warning_message(message=msg, parent=self)

    def handle_receive_top_6(self, ls):
        self.gif_animation.accept()
        self.display_images(ls)

    def handle_continue_process(self):
        if not self.bayesian_obj:
            return self.show_warning_message(message='请先执行初始化', parent=self, only_yes=True)
        chosen_images = []
        for i, group_box in enumerate([
            self.group_box_1,
            self.group_box_2,
            self.group_box_3,
            self.group_box_4,
            self.group_box_5,
            self.group_box_6,
            ]):
            if group_box.isChecked():
                chosen_images.append(self.latest_top_6[i])
        if not chosen_images:
            return self.show_warning_message(message='请选择感兴趣的相关图片', title='请选则图片', parent=self, only_yes=True)
        self.service.load(obj=self.bayesian_obj, ls=chosen_images, action='continue')
        self.service.start()
        self.gif_animation.exec_()

    def display_app_info(self):
        return self.show_info_message(message=f'软件名称: <b>{config.app_name_cn}</b><br>软件版本: <b>{config.app_version}</b>',
                                      title='关于本软件', parent=self, only_yes=True)

    def display_author_info(self):
        return self.show_info_message(message=f'作者: <b>{config.author_name}</b><br>所属单位: <b>{config.author_org}</b>',
                                      title='关于作者', parent=self, only_yes=True)






if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    m = MainApp()
    m.show()
    app.exec_()